package com.shop.shopcommon.context;

import com.shop.shopcommon.token.CustomUser;
import com.shop.shopcommon.token.PhoneVerificationToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Map;

/**
 * 登陆成功后用户信息保存在SecurityContext，该工具类封装了获取用户信息的方法
 */
@Slf4j
public class SecurityContext {
    /**
     * 获取当前登录用户名
     * @return 当前登录用户名
     */
    public static String getUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 当前用户未认证时，返回null
        if (!authentication.isAuthenticated()) {
            return null;
        }
        // 用户名密码登录
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            System.out.println(authentication);
            return userDetails.getUsername();
        }
        // 手机号验证码登录
        if (authentication instanceof PhoneVerificationToken) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            System.out.println(authentication);
            return userDetails.getUsername();
        }
        return null;
    }

    /**
     * 获取当前登录用户id
     * @return 当前登录用户id
     */
    public static Long getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 当前用户未认证时，返回null
        if (!authentication.isAuthenticated()) {
            return null;
        }
        log.info(String.valueOf(authentication));
        // 用户名密码登录
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            Object details = authentication.getDetails();
            if (details==null){
                return null;
            }
            if (details instanceof Map){
                return (Long) ((Map<?, ?>) details).get("id");
            }
        }
        // 手机号验证码登录
        if (authentication instanceof PhoneVerificationToken) {
            Object details = authentication.getDetails();
            if (details==null){
                return null;
            }
            if (details instanceof Map){
                return (Long) ((Map<?, ?>) details).get("id");
            }
        }
        return null;
    }

}
